
var console = window.console || { log: function () {} };
function HeadPicker(){}
HeadPicker.prototype = {
    initHeadPicker:function(opts){
        //图片比例
        this.$aspectRatio = opts.aspectRatio;
        //是否开圆形遮罩
        this.$circular = opts.circular;
        //是否显示辅助线
        this.$guides = opts.guides;
        //图片访问地址
        this.$imgHost = opts.host;
        //OSS上传授权服务接口
        this.$accessApi = opts.accessApi;
        //图像数据缓存
        this.$imgJsonData = null;

        //文件最大值
        this.$maxFileSize = opts.maxFileSize;
        //图片质量
        this.$imageQuality = opts.imageQuality;
        //图片选择器
        this.$fileChooseInput = opts.fileChooseInput;
        //原始图片容器
        this.$orignImgContainer = opts.orignImgContainer;
        //预览容器组
        this.$previewImgContainers =opts.previewImgContainers;
        //旋转按钮[L,R]
        this.$rotateBtns = opts.rotateBtns;
        //完成按钮
        this.$completeBtn = opts.completeBtn;

        //图片选择回调
        this.$picChooseCallBack = opts.picChooseCallBack;
        //授权回调
        this.$accessCallBack = opts.accessCallBack;
        //上传回调
        this.$uploadCallBack = opts.uploadCallBack;

        //初始化代理事件
        this.initProxyEvent();
    },
    initProxyEvent:function () {
        //图片选择器的代理事件
        this.$fileChooseInput.on('change', $.proxy(this.chooseFile, this));
        //图片旋转事件
        this.$rotateBtns.on('click', $.proxy(this.rotate, this));
        //完成裁剪按钮
        this.$completeBtn.on('click', $.proxy(this.completeCropper, this));
    },
    chooseFile:function () {
        var _this = this;
        var file,files;
        //获取文件列表
        files = _this.$fileChooseInput.prop('files');
        console.log(files);
        if(files.length==0)
        {
           return;
        }
        file = files[0];
        //检查文件合法性
        if(!_this.testImageFile(file))
        {
            this.$picChooseCallBack("选择的文件不能大于"+_this.$maxFileSize/1024 + "KB");
            return;
        }

        if (_this.url) {
            URL.revokeObjectURL(this.url); // Revoke the old one
        }
        _this.url = this.url = URL.createObjectURL(file);
        _this.startCropper();

    },
    startCropper:function () {
        var _this = this;

        if(_this.active)
        {
            _this.$orignImgContainer.cropper('replace',this.url);
        }
        else
        {
            _this.$orignImgContainer.attr('src',_this.url);
            //初始化cropper
            _this.$orignImgContainer.cropper({
                aspectRatio: _this.$aspectRatio,
                preview: _this.$previewImgContainers.selector,
                strict: false,
                guides:_this.$guides,
                crop: function (data) {
                    //缓存区域数据
                    _this.$imgJsonData = data;

                    if(_this.$circular == true)
                    {
                        $('.cropper-view-box').css('border-radius','50%');
                        $('.cropper-face').css('border-radius','50%');
                    }

                }
            });
            //标记裁剪容器已经初始化完成
            this.active = true;
        }



    },
    testImageFile:function (file) {
        var _this = this;
        //检查文件大小和文件类型
        if(file.size>_this.$maxFileSize)
        {
            return false;
        }
        if (file.type) {
            return /^image\/\w+$/.test(file.type);
        } else {
            return /\.(jpg|jpeg|png)$/.test(file);
        }
    },
    completeCropper:function () {
        var _this = this;
        if(_this.$imgJsonData == null)
        {
            return;
        }
        //开始处理图像数据
        _this.processImg();
    },
    rotate:function (e) {
        var _this = this;
        var data;
        if(_this.active)
        {
            data = $(e.target).data();
            if (data.method) {
                this.$orignImgContainer.cropper(data.method, data.option);
            }
        }
    },
    processImg:function () {
        var _this = this;
        //获取canvas对象
        var canvas = this.$orignImgContainer.cropper('getCroppedCanvas',_this.$imgJsonData);
        if(canvas)
        {
            //转换为blob对象
            canvas.toBlob(function(blob) {
                console.log(blob);
                //请求授权接口
                _this.getAccessKey(blob);
            },"image/jpeg", _this.$imageQuality);
        }
    },
    getAccessKey:function (blob) {
        var _this = this;
        $.ajax({
            url:_this.$accessApi,
            type:"POST",
            dataType:"json",
            success:function(data){
                //开始上传图片
                _this.upload(blob,data);
            },
            error:function(){
                _this.$accessCallBack("授权上传图片失败")
            }
        });
    },
    getRandomFileName:function (len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    upload:function (blob,accessdata) {
        var _this = this;
        var url = accessdata.host;
        var oMyForm = new FormData();
        var filename = this.getRandomFileName(32) + '.jpg';
        oMyForm.append("key",accessdata.dir+filename);
        oMyForm.append("Signature", accessdata.signature);
        oMyForm.append("OSSAccessKeyId", accessdata.accessid);
        oMyForm.append("policy", accessdata.policy);
        oMyForm.append("file", blob);
        oMyForm.append("success_action_status", 200);
        $.ajax(url, {
            type: 'POST',
            data: oMyForm,
            processData: false,
            contentType: false,
            success: function (data,textStatus,xhr) {
                console.log(xhr.status);
                if(xhr.status==200)
                {
                    _this.$uploadCallBack("保存成功",_this.$imgHost+accessdata.dir+filename);

                }else{
                    _this.$uploadCallBack("保存失败");
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('upload failed');
                console.log(xhr.responseText);
            },
        });
    },
    getImgBlob:function (callback) {
        var canvas = this.$orignImgContainer.cropper('getCroppedCanvas',this.$imgJsonData);
        var _this = this;
        if(canvas)
        {
            //转换为blob对象
            canvas.toBlob(function(blob) {
                callback(blob);
            },"image/jpeg", this.$imageQuality);
        }
    },
    getImgDataUrl:function () {
        var canvas = this.$orignImgContainer.cropper('getCroppedCanvas',this.$imgJsonData);
        if(canvas)
        {
            var base64Data = canvas.toDataURL('image/jpeg');
            return base64Data;
        }
        return null;
    }
};






